﻿Public Class SecuritySiteControl

    Private WithEvents _businessData As MetaQuery
    Public Property QueryName() As String
    Public Property KeyFieldName() As String
    Public Property ParentFieldName() As String
    Public Property GridActionOptionList() As CommonExt.Base.ActionOptionList
    Public Property DefaultActionOptionList() As CommonExt.Base.ActionOptionList
    Public Property TreeContextMenu As TreeListMenu
    Public Property PanelName() As String

    Dim pl As SystemBoxSDK.PL.MetaSDK.MetaUserSite_PL = Nothing

    Private Sub ContextMenuReload(ByVal sender As Object, ByVal e As EventArgs)
        ReloadTree()
    End Sub
    Public Sub ReloadTree()
        Me.Cursor = Cursors.WaitCursor
        TreeList1.DataSource = Nothing
        InitData()
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub ContextMenuExportToExcel(ByVal sender As Object, ByVal e As EventArgs)
        Dim filename As String
        Try
            filename = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), QueryName + ".xls")

            TreeList1.OptionsPrint.AutoWidth = False
            TreeList1.OptionsPrint.PrintAllNodes = True
            TreeList1.OptionsPrint.PrintFilledTreeIndent = True
            TreeList1.OptionsPrint.PrintTreeButtons = False
            TreeList1.ExportToXls(filename)

            MessageWindow.ShowMessage(String.Format("Export To Excel Succesfull.{0}{0}Your Filename is: {1}", vbCrLf, filename), MsgBoxStyle.Information)

        Catch ex As Exception
            Throw ex
        End Try
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub InitActionOption()
        Dim act As ActionOption
        GridActionOptionList = New CommonExt.Base.ActionOptionList()
        DefaultActionOptionList = New CommonExt.Base.ActionOptionList()
        act = New ActionOption("TreeOption", "ACT_00155", "Reload Data", AddressOf ContextMenuReload, True, True)
        DefaultActionOptionList.Add(act)
        act = New ActionOption("TreeOption", "ACT_00156", "Export to Excel", AddressOf ContextMenuExportToExcel, True, True)
        DefaultActionOptionList.Add(act)
    End Sub
    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        TreeList1.ForceInitialize()
        InitActionOption()
    End Sub

    Public Sub New(ByVal aQueryname As String)
        Me.New()
        QueryName = aQueryname
    End Sub

    Public Sub InitData()
        Dim hideCol As Boolean
        Dim colname As String
        Dim Column As DevExpress.XtraTreeList.Columns.TreeListColumn
        Dim colVisible As Boolean

        TreeList1.BeginUpdate()

        _businessData = MetaQuery.GetMetaQueryByName(QueryName)
        _businessData.FillResultQuery()
        TreeList1.KeyFieldName = KeyFieldName
        TreeList1.ParentFieldName = ParentFieldName
        TreeList1.DataSource = _businessData.ResultQuery

        TreeList1.OptionsBehavior.EnableFiltering = True

        'Dim fc12 As FilterCondition = New FilterCondition(FilterConditionEnum.Contains, colLOCATION, "San Francisco")

        ' TreeList1.RefreshDataSource()
        ' TreeList1.PopulateColumns(
        ' TreeList1.BestFitColumns()
        TreeList1.Columns.Clear()
        For Each row As DataRow In _businessData.MetaColumns.Rows
            colname = row("ColumnName").ToString
            hideCol = False
            If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                If colname.EndsWith("_ALT") Then
                    hideCol = True
                End If
            Else
                If colname.EndsWith("_PRM") Then
                    hideCol = True
                End If
            End If
            If hideCol = False Then
                colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
                Column = TreeList1.Columns.AddField(colname)
                Column.VisibleIndex = CInt(row("pOrder"))
                Column.Caption = row("pCaption").ToString
                Column.Visible = colVisible
                Column.Width = CInt(row("pWidth"))
                'Column.ToolTip = row("pToolTip").ToString

                Column.AllowIncrementalSearch = True
                Column.OptionsColumn.AllowEdit = False
                Column.OptionsColumn.ShowInCustomizationForm = True

                Column.Format.FormatType = GetFormatType(row)
                Column.Format.FormatString = row("pNumberFormat").ToString

                'formatType = GetFormatType(row)
                '
                'Column.DisplayFormat.FormatType = formatType
                'Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
            End If
        Next
        TreeList1.EndUpdate()
    End Sub

    Private Sub DoShowMainViewMenu(ByVal hi As TreeListHitInfo)
        Dim item As DXMenuItem
        Dim grpName As String = String.Empty
        Dim lvl As Integer
        '
        TreeContextMenu = New DevExpress.XtraTreeList.Menu.TreeListMenu(TreeList1)
        If GridActionOptionList IsNot Nothing Then

            lvl = TreeList1.FocusedNode.Level

            If lvl = 0 Then
                For Each action As CommonExt.Base.ActionOption In DefaultActionOptionList
                    item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
                    item.Enabled = action.Enabled
                    'Add new Group Separator when Group Name change
                    If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
                        item.BeginGroup = True
                    End If
                    grpName = action.OptionGroup
                    TreeContextMenu.Items.Add(item)
                Next
            End If
            ''Add Action Option that need the grid DataRow
            'For Each action As CommonExt.Base.ActionOption In Me.GridActionOptionList
            '    item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
            '    item.Tag = TreeList1.FocusedNode()
            '    item.Enabled = action.Enabled
            '    'item.Image = action.OptionIcon
            '    If item.Tag Is Nothing Then
            '        item.Enabled = False
            '    End If
            '    'Add new Group Separator when Group Name change
            '    If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
            '        item.BeginGroup = True
            '    End If
            '    grpName = action.OptionGroup
            '    If String.IsNullOrEmpty(action.QueryName) OrElse action.QueryName = GridView1.Tag.ToString Then
            '        ContextMenu.Items.Add(item)
            '    End If
            'Next
            'Display Menu
            TreeContextMenu.Show(hi.MousePoint)
        End If
    End Sub
    Private Function GetFormatType(ByVal arow As DataRow) As DevExpress.Utils.FormatType
        If (Not String.IsNullOrEmpty(arow("pNumberFormatID_FK").ToString)) Then
            Select Case CType(arow("pNumberFormatID_FK"), Guid)

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_CURRENCY, CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALNUMBER, CommonExt.Base.IdRepository.META_NUMBERFORMAT_PERCENT, CommonExt.Base.IdRepository.META_NUMBERFORMAT_STANDARD, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SCIENTIFIC
                    Return DevExpress.Utils.FormatType.Numeric

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTTIME
                    Return DevExpress.Utils.FormatType.DateTime

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_FORMATEXPR
                    Return DevExpress.Utils.FormatType.Custom

                Case Else
                    Return DevExpress.Utils.FormatType.None
            End Select
        Else
            Return DevExpress.Utils.FormatType.None
        End If
    End Function

    Private Sub TreeListExt_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        InitData()
    End Sub


    Private Sub PopulateDetailSection(ByVal node As TreeListNode)

        pl = Nothing
        Dim siteGUID As Guid = DirectCast(node.GetValue(Me.KeyFieldName), Guid)

        pl = New SystemBoxSDK.PL.MetaSDK.MetaUserSite_PL("MetaUserSite")
        pl.SQLWhere = String.Format("SiteID_FK = '{0}'", siteGUID)
        pl.SiteId_FK = siteGUID

        Dim aGridControl As GridExtPL = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = pl, .Name = "MetaUserSite"}
        aGridControl.SecureGrid = True

        AddHandler aGridControl.MasterCellValueChanged, AddressOf MasterCellValueChanged
        AddHandler aGridControl.InitNewMasterRow, AddressOf InitNewMasterRow

        'On trouve la form pour effacer les controle dedans et ensuite remettre le bon.
        'Comme ca on change le Detail selon la ligne dans L'explorer
        For Each aFrm As XtraForm In Me.ParentForm.MdiChildren
            If aFrm.Name = PanelName Then
                aFrm.Controls.Clear()
                aFrm.Controls.Add(aGridControl)
                aFrm.Show()
                aFrm.Focus()
            End If
            aFrm.Refresh()
        Next
    End Sub


    Private Sub TreeList1_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TreeList1.KeyUp
        If e.Control And e.Alt And e.KeyCode = Keys.Q Then
            Dim message As String
            message = String.Concat("MetaQuery: ", Me.QueryName, vbCrLf)
            MessageWindow.ShowMessage(message, MsgBoxStyle.Information)
        End If
    End Sub

    Private Sub TreeList1_MouseClick(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles TreeList1.MouseClick
        Dim hitInfo As TreeListHitInfo = TreeList1.CalcHitInfo(e.Location)
        Dim node As TreeListNode = TreeList1.FocusedNode

        If e.Button = MouseButtons.Left Then
            'DataRow = TreeList1.g.GetFocusedDataRow()
            'Dim imExplorer As IMExplorer = New IMExplorer(DataRow)
            If hitInfo.HitInfoType = HitInfoType.Cell Then
                Me.Cursor = Cursors.WaitCursor
                PopulateDetailSection(node)
                Me.Cursor = Cursors.Default
            End If
        End If
    End Sub

    Private Sub MasterCellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)
        Dim aView As GridView = DirectCast(sender, GridView)
        Dim aRow As System.Data.DataRow = aView.GetDataRow(e.RowHandle)

        If aRow.Table.TableName = "MetaUserSite" Then
            If aRow IsNot Nothing AndAlso e.Column.FieldName.Contains("Allow") Then
                If e.Column.FieldName = "AllowAll" Then
                    If CBool(e.Value) Then
                        aRow("AllowCreate") = True
                        aRow("AllowRead") = True
                        aRow("AllowUpdate") = True
                        aRow("AllowDelete") = True
                    Else
                        aRow("AllowCreate") = False
                        aRow("AllowRead") = False
                        aRow("AllowUpdate") = False
                        aRow("AllowDelete") = False
                    End If

                ElseIf Not CBool(e.Value) Then
                    'If ONE of the Allow column is not checked we set column AllowAll to false
                    aRow("AllowAll") = False

                ElseIf CBool(aRow("AllowCreate")) = True AndAlso CBool(aRow("AllowRead")) = True AndAlso CBool(aRow("AllowUpdate")) = True AndAlso CBool(aRow("AllowUpdate")) = True Then
                    'If ALL of the Allow column are checked we set column AllowAll to true
                    aRow("AllowAll") = True

                End If


            End If
        End If


    End Sub

    Private Sub InitNewMasterRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()
        'Using mc As PLSDK.PL.MetaSDK.MetaControlProps_PL = New PLSDK.PL.MetaSDK.MetaControlProps_PL()
        pl.NewRecord(row)
        'End Using
    End Sub

End Class
